<template>
  <el-popover
    popper-class="switch-company-popper"
    placement="bottom"
    width="200"
    trigger="click"
    transition="el-zoom-in-top"
    :hide-after="0"
    :disabled="!canChange"
  >
    <div class="company-list">
      <div v-for="item in showList" class="company-list-item" :key="item.id">
        <el-button
          link
          :type="item.id === company.id ? 'primary' : undefined"
          :disabled="!item.available || item.id === company.id"
          @click="hanldeClick(item)"
        >
          {{ item.name }}
        </el-button>
        <span v-if="!item.available" class="comment">
          当前组织暂无权限使用该系统
        </span>
      </div>
    </div>
    <template #reference>
      <el-button link class="company-btn">
        <span class="company-name" :title="company.name">
          {{ company.name }}
        </span>
        <el-icon v-if="canChange"><Switch /></el-icon>
      </el-button>
    </template>
  </el-popover>
</template>

<script setup>
import { ElMessageBox } from 'element-plus';

const props = defineProps({
  company: {
    type: Object,
    default: () => {}
  },
  companyList: {
    type: Array,
    default: () => []
  }
});

const showList = computed(() => {
  return props.companyList.filter(item => item.available);
});

const canChange = computed(() => {
  return showList.value.length > 1;
});

function hanldeClick(company) {
  ElMessageBox.confirm(`确定切换到【${company.name}】公司？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 线上可测 本地调试跳转 proxy 地址
      // const baseUrl = 'http://172.18.1.152:8080';
      window.location = `/oauth2/ex_company?company_id=${
        company.id
      }&callback=${encodeURIComponent(location.href)}`;
    })
    .catch(() => {});
}
</script>

<style lang="scss" scoped>
.company-name {
  color: #606266;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  white-space: initial;
  text-align: justify;
}
.company-list {
  display: flex;
  flex-direction: column;
}
.company-list-item {
  cursor: auto;
  margin: 0 -12px;
  position: relative;
  .el-button {
    padding: 0;
    width: 100%;
    height: 100%;
    justify-content: flex-start;
    padding: 7px 10px;
    line-height: 16px;
    white-space: initial;
    text-align: justify;
    word-break: break-all;
  }
  .comment {
    font-size: 12px;
    line-height: 20px;
    position: absolute;
    bottom: 3px;
    left: 20px;
    color: #c0c4cc;
  }
  &:hover {
    background-color: #efefef;
    cursor: pointer;
  }
}
.el-icon-arrow-right {
  margin-left: 0;
}
.company-btn {
  font-weight: 800;
  margin-right: 15px;
  i {
    margin-left: 3px;
  }
}
</style>
